package com.eve.util.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.zip.GZIPInputStream;

public class HTTPHelper {

	private static Logger log = LoggerFactory.getLogger(HTTPHelper.class);

	private static int CONN_TIMEOUT = 10 * 1000;
	private static int SO_TIMEOUT = 120 * 1000;

	public static ThreadLocal connTimeoutTl = new ThreadLocal();
	public static ThreadLocal soTimeoutTl = new ThreadLocal();

	private CookieManager cookieManager = new CookieManager();

	public void clearCookie() {
		cookieManager.clear();
	}

	public String getCookie(String url) {
		return cookieManager.getStoredCookies(url);
	}

	public String httpGet(String url, Map<String, String> headerParams,
			String[] proxyParams) {

		Map<String, String> resultMap = httpGetWithResponseMap(url,
				headerParams, proxyParams, true);
		if (!resultMap.containsKey("status")) {
			return null;
		}
		String status = resultMap.get("status");
		if (Integer.valueOf(status) < 400) {
			return resultMap.get("html");
		}
		return "";
	}

	public String httpPost(String url, String params,
			Map<String, String> headerParams, String[] proxyParams) {

		Map<String, String> resultMap = httpPostWithResponseMap(url, params,
				headerParams, proxyParams, true);
		if (!resultMap.containsKey("status")) {
			return null;
		}
		String status = resultMap.get("status");
		if (Integer.valueOf(status) < 400) {
			return resultMap.get("html");
		}
		return "";
	}

	public Map<String, String> httpGetWithResponseMap(String url,
			Map<String, String> headerParams, String[] proxyParams,
			String encode, boolean... extraParams) {
		if (StringUtils.isEmpty(encode)) {
			encode = "utf-8";
		}
		log.debug("Get Thread=" + Thread.currentThread().getName() + ", url="
				+ url);
		Map<String, String> resultMap = new HashMap<String, String>();
		boolean ssl = false;
		if (url.toLowerCase().startsWith("https")) {
			ssl = true;
		}
		DefaultHttpClient client = null;
		if (extraParams != null && extraParams.length > 0) {
			client = getHttpClient(extraParams[0], ssl, proxyParams);
		} else {
			client = getHttpClient(false, ssl, proxyParams);
		}

		HttpGet httpGet = new HttpGet(url);
		// 添加Accept-Encoding
		if (headerParams == null
				|| !headerParams.containsKey("Accept-Encoding")) {
			httpGet.addHeader("Accept-Encoding", "gzip");
		}
		// 添加cookie
		if (headerParams == null || !headerParams.containsKey("Cookie")) {
			String cookie = cookieManager.getStoredCookies(url);
			if (!StringUtils.isBlank(cookie)) {
				httpGet.addHeader("Cookie", cookie);
			}
		}

		if (headerParams != null) {
			Set<String> keys = headerParams.keySet();
			for (String key : keys) {
				httpGet.addHeader(key, headerParams.get(key));
			}
		}

		try {
			HttpResponse response = client.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			resultMap.put("status", statusCode + "");
			Header[] headers = response.getAllHeaders();
			cookieManager.storeCookies(url, headers);
			for (Header header : headers) {
				if (!"Set-Cookie".equals(header.getName())) {
					resultMap.put(header.getName(), header.getValue());
				}
			}

			HttpEntity httpEntity = response.getEntity();
			String contentEncoding = getContentEncoding(httpEntity);
			if (contentEncoding.indexOf("gzip") > -1) {
				response.setEntity(new GzipEntity(httpEntity));
			}
			String html = EntityUtils.toString(response.getEntity(), encode);
			log.debug("Get Thread=" + Thread.currentThread().getName()
					+ ", html=" + html);
			resultMap.put("html", html);

		} catch (Exception e) {
			log.error("error occured", e);
			throw new RuntimeException(e);

		} finally {
			client.getConnectionManager().closeExpiredConnections();
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	public Map<String, String> httpGetWithResponseMap(String url,
			Map<String, String> headerParams, String[] proxyParams,
			boolean... extraParams) {
		log.debug("Get Thread=" + Thread.currentThread().getName() + ", url="
				+ url);
		Map<String, String> resultMap = new HashMap<String, String>();
		boolean ssl = false;
		if (url.toLowerCase().startsWith("https")) {
			ssl = true;
		}
		DefaultHttpClient client = null;
		if (extraParams != null && extraParams.length > 0) {
			client = getHttpClient(extraParams[0], ssl, proxyParams);
		} else {
			client = getHttpClient(false, ssl, proxyParams);
		}

		HttpGet httpGet = new HttpGet(url);
		// 添加Accept-Encoding
		if (headerParams == null
				|| !headerParams.containsKey("Accept-Encoding")) {
			httpGet.addHeader("Accept-Encoding", "gzip");
		}
		// 添加cookie
		if (headerParams == null || !headerParams.containsKey("Cookie")) {
			String cookie = cookieManager.getStoredCookies(url);
			if (!StringUtils.isBlank(cookie)) {
				httpGet.addHeader("Cookie", cookie);
			}
		}

		if (headerParams != null) {
			Set<String> keys = headerParams.keySet();
			for (String key : keys) {
				httpGet.addHeader(key, headerParams.get(key));
			}
		}

		try {
			HttpResponse response = client.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			resultMap.put("status", statusCode + "");
			Header[] headers = response.getAllHeaders();
			cookieManager.storeCookies(url, headers);
			for (Header header : headers) {
				if (!"Set-Cookie".equals(header.getName())) {
					resultMap.put(header.getName(), header.getValue());
				}
			}

			HttpEntity httpEntity = response.getEntity();
			String contentEncoding = getContentEncoding(httpEntity);
			if (contentEncoding.indexOf("gzip") > -1) {
				response.setEntity(new GzipEntity(httpEntity));
			}
			String html = EntityUtils.toString(response.getEntity());
			log.debug("Get Thread=" + Thread.currentThread().getName()
					+ ", html=" + html);
			resultMap.put("html", html);

		} catch (Exception e) {
			log.error("error occured", e);
			throw new RuntimeException(e);

		} finally {
			client.getConnectionManager().closeExpiredConnections();
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	public static String ENCODE = "encode";// 返回数据编码
	public static String CertPath = "certPath";// 证书路径
	public static String CertPassword = "certPassword";// 证书密码

	public Map<String, String> httpPostContentWithResponseMap(
			Map<String, Object> httpParamMap, String url, String params,
			Map<String, String> headerParams, String[] proxyParams,
			boolean... extraParams) {
		if (httpParamMap == null) {
			httpParamMap = new HashMap();
		}
		String encode = (String) httpParamMap.get(ENCODE);
		if (StringUtils.isEmpty(encode)) {
			encode = "utf-8";
		}

		String certPath = (String) httpParamMap.get(CertPath);
		if (StringUtils.isEmpty(certPath)) {
			encode = "utf-8";
		}

		String certPassword = (String) httpParamMap.get(CertPassword);
		if (StringUtils.isEmpty(certPassword)) {
			encode = "utf-8";
		}
		log.debug("httpPost Thread=" + Thread.currentThread().getName()
				+ ", url=" + url);
		Map<String, String> resultMap = new HashMap<String, String>();

		boolean ssl = false;
		if (url.toLowerCase().startsWith("https")) {
			ssl = true;
		}
		DefaultHttpClient client = null;
		if (extraParams != null && extraParams.length > 0) {
			if (!StringUtils.isEmpty(certPath) && ssl) {
				client = this.getSslHttpClient(certPath, certPassword,
						extraParams[0], proxyParams);
			} else {
				client = getHttpClient(extraParams[0], ssl, proxyParams);
			}
		} else {
			if (!StringUtils.isEmpty(certPath) && ssl) {
				client = this.getSslHttpClient(certPath, certPassword, false,
						proxyParams);
			} else {
				client = getHttpClient(false, ssl, proxyParams);
			}

		}
		HttpPost httpPost = new HttpPost(url);
		// 添加Accept-Encoding
		if (headerParams == null
				|| !headerParams.containsKey("Accept-Encoding")) {
			httpPost.addHeader("Accept-Encoding", "gzip");
		}
		// 添加cookie
		if (headerParams == null || !headerParams.containsKey("Cookie")) {
			String cookie = cookieManager.getStoredCookies(url);
			if (!StringUtils.isBlank(cookie)) {
				httpPost.addHeader("Cookie", cookie);
			}
		}

		if (headerParams != null) {
			Set<String> keys = headerParams.keySet();
			for (String key : keys) {
				httpPost.addHeader(key, headerParams.get(key));
			}
		}

		try {
			HttpEntity entity = new ByteArrayEntity(params.getBytes());

			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			resultMap.put("status", statusCode + "");
			Header[] headers = response.getAllHeaders();
			cookieManager.storeCookies(url, headers);
			for (Header header : headers) {
				if (!"Set-Cookie".equals(header.getName())) {
					resultMap.put(header.getName(), header.getValue());
				}
			}

			HttpEntity httpEntity = response.getEntity();
			String contentEncoding = getContentEncoding(httpEntity);
			if (contentEncoding.indexOf("gzip") > -1) {
				response.setEntity(new GzipEntity(httpEntity));
			}
			// String html = EntityUtils.toString(response.getEntity());
			String html = EntityUtils.toString(response.getEntity(), encode);
			log.debug("Post Thread=" + Thread.currentThread().getName()
					+ ", html=" + html);
			resultMap.put("html", html);

		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException(e);

		} finally {
			client.getConnectionManager().closeExpiredConnections();
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	public Map<String, String> httpPostContentWithResponseMapByEncode(
			String url, String params, Map<String, String> headerParams,
			String[] proxyParams, String encode, boolean... extraParams) {
		if (StringUtils.isEmpty(encode)) {
			encode = "utf-8";
		}
		log.debug("httpPost Thread=" + Thread.currentThread().getName()
				+ ", url=" + url);
		Map<String, String> resultMap = new HashMap<String, String>();

		boolean ssl = false;
		if (url.toLowerCase().startsWith("https")) {
			ssl = true;
		}

		DefaultHttpClient client = null;
		if (extraParams != null && extraParams.length > 0) {
			client = getHttpClient(extraParams[0], ssl, proxyParams);
		} else {
			client = getHttpClient(false, ssl, proxyParams);
		}

		HttpPost httpPost = new HttpPost(url);
		// 添加Accept-Encoding
		if (headerParams == null
				|| !headerParams.containsKey("Accept-Encoding")) {
			httpPost.addHeader("Accept-Encoding", "gzip");
		}
		// 添加cookie
		if (headerParams == null || !headerParams.containsKey("Cookie")) {
			String cookie = cookieManager.getStoredCookies(url);
			if (!StringUtils.isBlank(cookie)) {
				httpPost.addHeader("Cookie", cookie);
			}
		}

		if (headerParams != null) {
			Set<String> keys = headerParams.keySet();
			for (String key : keys) {
				httpPost.addHeader(key, headerParams.get(key));
			}
		}

		try {
			HttpEntity entity = new ByteArrayEntity(params.getBytes());

			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			resultMap.put("status", statusCode + "");
			Header[] headers = response.getAllHeaders();
			cookieManager.storeCookies(url, headers);
			for (Header header : headers) {
				if (!"Set-Cookie".equals(header.getName())) {
					resultMap.put(header.getName(), header.getValue());
				}
			}

			HttpEntity httpEntity = response.getEntity();
			String contentEncoding = getContentEncoding(httpEntity);
			if (contentEncoding.indexOf("gzip") > -1) {
				response.setEntity(new GzipEntity(httpEntity));
			}
			// String html = EntityUtils.toString(response.getEntity());
			String html = EntityUtils.toString(response.getEntity(), encode);
			log.debug("Post Thread=" + Thread.currentThread().getName()
					+ ", html=" + html);
			resultMap.put("html", html);

		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException(e);

		} finally {
			client.getConnectionManager().closeExpiredConnections();
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	public Map<String, String> httpPostContentWithResponseMap(String url,
			String params, Map<String, String> headerParams,
			String[] proxyParams, boolean... extraParams) {
		log.debug("httpPost Thread=" + Thread.currentThread().getName()
				+ ", url=" + url);
		Map<String, String> resultMap = new HashMap<String, String>();

		boolean ssl = false;
		if (url.toLowerCase().startsWith("https")) {
			ssl = true;
		}

		DefaultHttpClient client = null;
		if (extraParams != null && extraParams.length > 0) {
			client = getHttpClient(extraParams[0], ssl, proxyParams);
		} else {
			client = getHttpClient(false, ssl, proxyParams);
		}

		HttpPost httpPost = new HttpPost(url);
		// 添加Accept-Encoding
		if (headerParams == null
				|| !headerParams.containsKey("Accept-Encoding")) {
			httpPost.addHeader("Accept-Encoding", "gzip");
		}
		// 添加cookie
		if (headerParams == null || !headerParams.containsKey("Cookie")) {
			String cookie = cookieManager.getStoredCookies(url);
			if (!StringUtils.isBlank(cookie)) {
				httpPost.addHeader("Cookie", cookie);
			}
		}

		if (headerParams != null) {
			Set<String> keys = headerParams.keySet();
			for (String key : keys) {
				httpPost.addHeader(key, headerParams.get(key));
			}
		}

		try {
			HttpEntity entity = new ByteArrayEntity(params.getBytes());

			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			resultMap.put("status", statusCode + "");
			Header[] headers = response.getAllHeaders();
			cookieManager.storeCookies(url, headers);
			for (Header header : headers) {
				if (!"Set-Cookie".equals(header.getName())) {
					resultMap.put(header.getName(), header.getValue());
				}
			}

			HttpEntity httpEntity = response.getEntity();
			String contentEncoding = getContentEncoding(httpEntity);
			if (contentEncoding.indexOf("gzip") > -1) {
				response.setEntity(new GzipEntity(httpEntity));
			}
			// String html = EntityUtils.toString(response.getEntity());
			String html = EntityUtils.toString(response.getEntity(), "gbk");
			log.debug("Post Thread=" + Thread.currentThread().getName()
					+ ", html=" + html);
			resultMap.put("html", html);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			client.getConnectionManager().closeExpiredConnections();
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	public Map<String, String> httpPostWithResponseMap(String url,
			String params, Map<String, String> headerParams,
			String[] proxyParams, boolean... extraParams) {
		log.debug("httpPost Thread=" + Thread.currentThread().getName()
				+ ", url=" + url);
		Map<String, String> resultMap = new HashMap<String, String>();

		boolean ssl = false;
		if (url.toLowerCase().startsWith("https")) {
			ssl = true;
		}

		DefaultHttpClient client = null;
		if (extraParams != null && extraParams.length > 0) {
			client = getHttpClient(extraParams[0], ssl, proxyParams);
		} else {
			client = getHttpClient(false, ssl, proxyParams);
		}

		List<BasicNameValuePair> paramPair = null;
		if (!StringUtils.isBlank(params) && params.contains("&")) {
			paramPair = getParamPair(params);
		}

		HttpPost httpPost = new HttpPost(url);
		// 添加Accept-Encoding
		if (headerParams == null
				|| !headerParams.containsKey("Accept-Encoding")) {
			httpPost.addHeader("Accept-Encoding", "gzip");
		}
		// 添加cookie
		if (headerParams == null || !headerParams.containsKey("Cookie")) {
			String cookie = cookieManager.getStoredCookies(url);
			if (!StringUtils.isBlank(cookie)) {
				httpPost.addHeader("Cookie", cookie);
			}
		}

		if (headerParams != null) {
			Set<String> keys = headerParams.keySet();
			for (String key : keys) {
				httpPost.addHeader(key, headerParams.get(key));
			}
		}

		try {
			HttpEntity entity = null;
			if (paramPair != null) {
				entity = new UrlEncodedFormEntity(paramPair, "utf-8");
			} else {
				entity = new ByteArrayEntity(params.getBytes());
			}
			httpPost.setEntity(entity);
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			resultMap.put("status", statusCode + "");
			Header[] headers = response.getAllHeaders();
			cookieManager.storeCookies(url, headers);
			for (Header header : headers) {
				if (!"Set-Cookie".equals(header.getName())) {
					resultMap.put(header.getName(), header.getValue());
				}
			}

			HttpEntity httpEntity = response.getEntity();
			String contentEncoding = getContentEncoding(httpEntity);
			if (contentEncoding.indexOf("gzip") > -1) {
				response.setEntity(new GzipEntity(httpEntity));
			}
			String html = EntityUtils.toString(response.getEntity(),"utf-8");
			log.debug("Post Thread=" + Thread.currentThread().getName()
					+ ", html=" + html);
			resultMap.put("html", html);

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			client.getConnectionManager().closeExpiredConnections();
			client.getConnectionManager().shutdown();
		}
		return resultMap;
	}

	// ----------------------------------------------------------
	private static DefaultHttpClient getHttpClient(boolean followRedirects,
			boolean ssl, String... proxy) {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		// HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
		if (connTimeoutTl.get() != null) {
			HttpConnectionParams.setConnectionTimeout(params,
					(Integer) connTimeoutTl.get());
		} else {
			HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
		}
		if (soTimeoutTl.get() != null) {
			HttpConnectionParams.setSoTimeout(params,
					(Integer) soTimeoutTl.get());
		} else {
			HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
		}

		HttpClientParams.setRedirecting(params, followRedirects);

		DefaultHttpClient client = new DefaultHttpClient(params);

		Scheme http = new Scheme("http", 80,
				PlainSocketFactory.getSocketFactory());
		Scheme https = new Scheme("https", 443, buildSSLSocketFactory());
		SchemeRegistry sr = client.getConnectionManager().getSchemeRegistry();
		sr.register(http);
		sr.register(https);

		if (proxy != null && proxy.length == 2) {
			HttpHost httpHost = new HttpHost(proxy[0],
					Integer.valueOf(proxy[1]), HttpHost.DEFAULT_SCHEME_NAME);
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					httpHost);
		} else {
			client.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
			client.getParams()
					.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}
		return client;
	}

	private DefaultHttpClient getSslHttpClient(String certPath,
			String certPassword, boolean followRedirects, String... proxy) {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		// HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
		// HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
		if (connTimeoutTl.get() != null) {
			HttpConnectionParams.setConnectionTimeout(params,
					(Integer) connTimeoutTl.get());
		} else {
			HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
		}
		if (soTimeoutTl.get() != null) {
			HttpConnectionParams.setSoTimeout(params,
					(Integer) soTimeoutTl.get());
		} else {
			HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
		}
		HttpClientParams.setRedirecting(params, followRedirects);

		DefaultHttpClient client = new DefaultHttpClient(params);

		Scheme http = new Scheme("http", 80,
				PlainSocketFactory.getSocketFactory());
		Scheme https = new Scheme("https", 443, buildSSLSocketFactory(certPath,
				certPassword));
		SchemeRegistry sr = client.getConnectionManager().getSchemeRegistry();
		sr.register(http);
		sr.register(https);

		if (proxy != null && proxy.length == 2) {
			HttpHost httpHost = new HttpHost(proxy[0],
					Integer.valueOf(proxy[1]), HttpHost.DEFAULT_SCHEME_NAME);
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					httpHost);
		} else {
			client.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
			client.getParams()
					.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}
		return client;
	}

	private static List<BasicNameValuePair> getParamPair(String params) {
		List<BasicNameValuePair> paramPair = new ArrayList<BasicNameValuePair>();
		String[] elments = params.split("&");
		for (String param : elments) {
			String[] str = param.split("=");
			if (str.length == 2) {
				try {
					paramPair.add(new BasicNameValuePair(str[0], URLDecoder
							.decode(str[1], "UTF-8")));
				} catch (UnsupportedEncodingException e) {
				}
			}
		}
		return paramPair;
	}

	private static SSLSocketFactory buildSSLSocketFactory(String certPath,
			String certPassword) {
		try {
 			FileInputStream instream = new FileInputStream(new File(certPath));
			 
			/*
			SSLSocketFactory sf = null;
			try {
				sf = new SSLSocketFactory(keyStore);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}*/

			KeyStore keyStore1 = KeyStore.getInstance("PKCS12");
 			try {
				keyStore1.load(instream, certPassword.toCharArray());

			} finally {
				instream.close();
			}
			instream = new FileInputStream(new File(certPath));
		 
			TrustManager tm = new X509TrustManager() {
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				@Override
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}
			};
			
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(keyStore1, certPassword.toCharArray());
		 

			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(kmf.getKeyManagers(),  new TrustManager[] {  tm}, new SecureRandom());
 			// Allow TLSv1 protocol only
			SSLSocketFactory sslsf = new SSLSocketFactory(sslcontext,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 			return sslsf;
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	private static SSLSocketFactory buildSSLSocketFactory() {
		TrustStrategy ts = new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] x509Certificates,
					String s) throws CertificateException {
				return true;
			}
		};
		SSLSocketFactory sf = null;
		try {
			sf = new SSLSocketFactory(ts,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		} catch (Exception e) {
		}
		return sf;
	}

	private String getContentEncoding(HttpEntity entity) {
		String contentEncoding = "";
		Header header = entity.getContentEncoding();
		if (header != null) {
			HeaderElement values[] = header.getElements();
			if (values.length > 0) {
				contentEncoding = values[0].getName();
			}
		}
		return contentEncoding;
	}

	static class GzipEntity extends HttpEntityWrapper {
		private HttpEntity wrappedEntity;

		public GzipEntity(HttpEntity wrapped) {
			super(wrapped);
			this.wrappedEntity = wrapped;
		}

		@Override
		public InputStream getContent() throws IOException {
			return new GZIPInputStream(wrappedEntity.getContent());
		}
	}


	public String httpPost(String url, String param) throws Exception{

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			conn.setConnectTimeout(CONN_TIMEOUT);
			conn.setReadTimeout(SO_TIMEOUT);
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}


}
